import moment from "moment";
/*
  设备管理-报表公共方法、属性
  在页面中先引入该文件：
  import { mixin } from '@/pages/comprehensiveReport/equipmentManagement/mixin'
  注册混入：mixins:[mixin]
*/
export const mixin = {
  methods: {
    // 公共方法写在这里
  },
};

/*
  设备管理-报表-公共的普通方法
  import { combinedFn } from '@/pages/comprehensiveReport/equipmentManagement/mixin'
*/

/**
 * @arr { [] }      表格渲染的所有字段
 * @list { [{}] }   表格的数据
 * @fields { [] }   需要转换为Number的字段集合
 */
export const combinedFn = (arr, list, fields = []) => {
  let combined = {};
  list = convertNumber(fields, list);
  arr.forEach((key) => {
    combined[key] = list.reduce((total, nowItem) => {
      if (fields.includes(key)) {
        if (String(nowItem[key]).indexOf(".") > -1) {
          const digit = String(nowItem[key]).split(".")[1].length;
          const m = Math.pow(10, digit);
          return Math.round((total * m + nowItem[key] * m) / m);
        } else {
          return total + Math.round(nowItem[key]);
        }
      } else {
        return "";
      }
    }, 0);
  });
  return {
    list,
    combined
  };
};

// 需要合计的字段：有些需要合计的数字，后端返回的是String，在这里统一将其转为Number 
export const convertNumber = (fields = [], list) => {
  fields.forEach((key) => {
    list.forEach((item) => {
      item[key] = Number(item[key]);
    });
  });
  return list;
};

// 转换时间格式
export const formatTime = (fields = [], list) => {
  fields.forEach((key) => {
    list.forEach((item) => {
      item[key] = moment(item[key]).format("YYYY-MM-DD");
    });
  });
  return list;
};
